package com.example.daniel.qrcodescan;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Air extends AppCompatActivity {

    private String TCP_SERVER_IP="192.168.12.179";
    private String USER_ID="1233";
    private int TCP_SERVER_PORT = 7654;
    private String lockerNumber;
    private String receivedMessage;

    public static String runTcpClient(String ip, int port, String msg) {
        try {
            {
                Socket s = new Socket(ip, port);


                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                //send output msg
                String outMsg = msg + System.getProperty("line.separator");
                out.write(outMsg);
                out.flush();
                Log.i("TcpClient", "sent: " + outMsg);

                s.close();
            }
            String inMsg = "";
            {
                Socket s = new Socket(ip, port);
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //accept server response
                String str;
                while ((str = in.readLine()) != null) {
                    inMsg += str;
                    inMsg += "\n";
                }
                inMsg += System.getProperty("line.separator");
                Log.i("TcpClient", "received: " + inMsg);
                //close connection
                s.close();
            }
            return inMsg;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ERROR!";
    }

    private  EditText edt=null;
    private Button confirm=null;
    private Button pickUp=null;
    private Button logInfo=null;
    private Button position=null;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present
        getMenuInflater().inflate(R.menu.menu_options, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.en:
                LanguageHandler.changeLocale(this.getResources(),"en");
                finish();
                startActivity(getIntent());
                return true;
            case R.id.cn:
                LanguageHandler.changeLocale(this.getResources(),"cn");
                finish();
                startActivity(getIntent());
                return true;
            case R.id.tw:
                LanguageHandler.changeLocale(this.getResources(),"tw");
                finish();
                startActivity(getIntent());
                return true;
            case R.id.home:
                Intent intent = new Intent(Air.this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
                return true;
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_air);

        Bundle bundle = getIntent().getExtras();
        receivedMessage = bundle.getString("Server");
        final String[] Server = receivedMessage.split(" ");
        lockerNumber=Server[2];
        TCP_SERVER_PORT=Integer.parseInt(Server[1]);
        TCP_SERVER_IP=Server[0];
        USER_ID=getAndroidId(Air.this);
        Log.i("TcpClient", "id is: " + USER_ID);

        edt=(EditText)findViewById(R.id.editText);
        confirm=(Button)findViewById(R.id.confirmButton);
        pickUp=(Button)findViewById(R.id.pickUp);
        logInfo=(Button)findViewById(R.id.logInfo);
        position=(Button)findViewById(R.id.currentPosition);

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String boardGate = edt.getText().toString();
                String command="TO";
                command=command.concat(boardGate+"_"+USER_ID);
                new CommandTask().execute(command);
            }
        });

        pickUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String command="OP";
                command=command.concat(lockerNumber+"_"+USER_ID);
                new CommandTask().execute(command);
            }
        });

        logInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String command="VLOG_";
                command=command.concat(USER_ID);
                new CommandTask().execute(command);
            }
        });

        position.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //original
//                String command="EQRY_";
//                command=command.concat(USER_ID);
//                new CommandTask().execute(command);
                //original
                ///
                Intent intent = new Intent(Air.this,currentPos.class);
                Bundle bundle=new Bundle();
                bundle.putString("Server", receivedMessage);
                intent.putExtras(bundle);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                /////
                startActivity(intent);
            }
        });
    }

    public class CommandTask extends AsyncTask<String, Integer, String>
    {
        protected String doInBackground(String... msg) {
            String returnR;
            String result=msg[0];
            returnR=runTcpClient(TCP_SERVER_IP, TCP_SERVER_PORT, msg[0]);
            result=result+" "+returnR;
            return result;
        }

        protected void onPostExecute(String result) {

//            Toast.makeText(AirAGV.this, result, Toast.LENGTH_SHORT).show();

            String[] str = result.split(" ");
            int head=str[0].length();
            String fromCar=result.substring(head+1);

            Log.i("TcpClient", "received: " + fromCar);
            String firstTwochars = str[0].substring(0, 2);
            if(firstTwochars.equals("TO")){
                Log.i("TcpClient", "TOhhhhhhhhhhhh" + fromCar+"hhhhhh");
                if(fromCar.substring(0,1).equals("Y")){
                    Toast.makeText(Air.this, getResources().getString(R.string.toY), Toast.LENGTH_SHORT).show();
                }else if(fromCar.substring(0,1).equals("N")){
                    Toast.makeText(Air.this, getResources().getString(R.string.toN), Toast.LENGTH_SHORT).show();
                }
            }else if(firstTwochars.equals("OP")){
                Log.i("TcpClient", "OP: " + fromCar);
                if(fromCar.substring(0,1).equals("N")){
                    Toast.makeText(Air.this, getResources().getString(R.string.opN)+"\n"+fromCar.substring(1), Toast.LENGTH_SHORT).show();
                }else{
                    ///////////////////////////////////////////
                }
            }else if(firstTwochars.equals("EQ")){
                Log.i("TcpClient", "POSITION: " + fromCar);
                showAlertDialog(fromCar);
            }else if(firstTwochars.equals("VL")){
                String[] lines = fromCar.split(System.getProperty("line.separator"));
                int i=0;
                int[] records = new int[100];
                for( i=0; i<100; i++ ){
                    records[i]=0;
                }
                int lenth=lines.length;
                for(i=0;i<lenth;i++){
                    String lastTwo=lines[i].substring(lines[i].length()-2);
                    int gate=Integer.parseInt(lastTwo);
                    records[gate]++;
                }
                fromCar+="\nRecords:\n";
                for(i=0;i<100;i++){
                    if(records[i] != 0){
                        String tobeAdded=Integer.toString(i);
                        tobeAdded += "      appears ";
                        tobeAdded += Integer.toString(records[i]);
                        tobeAdded += " times\n";
                        fromCar+=tobeAdded;
                    }
                }

                Log.i("TcpClient", "RECORDS: " + fromCar);
                showAlertDialog(fromCar);
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    }

    private void showAlertDialog(String message) {
        new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.app_name))
                .setCancelable(false)
                .setMessage(message)
                .setPositiveButton(getResources().getString(R.string.confirmBtn), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }

    public static String getAndroidId (Context context) {
        String ANDROID_ID = Settings.System.getString(context.getContentResolver(), Settings.System.ANDROID_ID);
        return ANDROID_ID;
    }
}